package com.probox.common.entity.service.order.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.probox.common.core.constant.CachePrefix;
import com.probox.common.core.constant.Constants;
import com.probox.common.core.enums.*;
import com.probox.common.core.exception.BaseException;
import com.probox.common.core.utils.DateUtils;
import com.probox.common.core.utils.SecurityUtils;
import com.probox.common.core.utils.StringUtils;
import com.probox.common.core.utils.money.MoneyUtils;
import com.probox.common.core.web.domain.AjaxResult;
import com.probox.common.entity.domain.customer.CustomerInfo;
import com.probox.common.entity.domain.customer.RechargeInfo;
import com.probox.common.entity.domain.order.OrderInfoParent;
import com.probox.common.entity.domain.order.OrderRecharge;
import com.probox.common.entity.domain.order.vo.OrderSettlementVo;
import com.probox.common.entity.domain.platfom.PlatformStore;
import com.probox.common.entity.domain.product.ProductInfo;
import com.probox.common.entity.domain.recharge.RechargeRecord;
import com.probox.common.entity.domain.recharge.RechargeRecordRights;
import com.probox.common.entity.mapper.order.OrderRechargeMapper;
import com.probox.common.entity.service.customer.ICustomerFundService;
import com.probox.common.entity.service.customer.ICustomerInfoService;
import com.probox.common.entity.service.customer.ICustomerLevelService;
import com.probox.common.entity.service.customer.IRechargeInfoService;
import com.probox.common.entity.service.order.IOrderInfoParentService;
import com.probox.common.entity.service.order.IOrderInfoService;
import com.probox.common.entity.service.order.IOrderRechargeService;
import com.probox.common.entity.service.platfom.IPlatformStoreService;
import com.probox.common.entity.service.product.IProductInfoService;
import com.probox.common.entity.service.recharge.IRechargeRecordRightsService;
import com.probox.common.entity.service.recharge.IRechargeRecordService;
import com.probox.common.entity.vo.customer.CustomerRechargeVo;
import com.probox.common.entity.vo.customer.RechargeRightItem;
import com.probox.common.redis.service.RedisService;
import com.probox.customer.api.domain.CustomerFundVo;
import com.probox.customer.api.domain.CustomerLevel;
import com.probox.platform.api.domain.PlatformStoreVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;



import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 充值订单Service业务层处理
 *
 * @author hds
 * @date 2021-06-07
 */
@Service
@Transactional
public class OrderRechargeServiceImpl extends ServiceImpl<OrderRechargeMapper, OrderRecharge> implements IOrderRechargeService {

    private static final Logger log = LoggerFactory.getLogger(OrderRechargeServiceImpl.class);

    @Autowired
    private OrderRechargeMapper orderRechargeMapper;

    @Autowired
    private IOrderInfoService orderInfoService;

    @Autowired
    private IPlatformStoreService platformStoreService;


    @Autowired
    private IRechargeInfoService rechargeInfoService;

    @Autowired
    private ICustomerInfoService iCustomerInfoService;

    @Autowired
    private IOrderInfoParentService orderInfoParentService;

    @Autowired
    private IRechargeRecordService rechargeRecordService;

    @Autowired
    private ICustomerFundService iCustomerFundService;

    @Autowired
    private ICustomerLevelService customerLevelService;


    @Autowired
    private RedisService redisService;


    @Autowired
    private IProductInfoService iProductInfoService;

    @Autowired
    private IRechargeRecordRightsService rechargeRecordRightsService;

    private static final String order_no_key = CachePrefix.PRE_GLOABLE + "order_no_";

    /**
     * 查询客户的消费记录
     *
     * @param customerUid
     * @return
     */
    @Override
    public List<CustomerRechargeVo> listConsumptionByUid(Long customerUid, String time) {
        return orderRechargeMapper.listConsumptionByUid(customerUid, time);
    }

    /**
     * 查询客户的余额消费记录
     *
     * @param customerUid
     * @return
     */
    @Override
    public List<CustomerRechargeVo> listBalanceChange(Long customerUid) {
        return orderRechargeMapper.listBalanceChange(customerUid);
    }


    /**
     * 查询用户的消费统计
     *
     * @param customerUid
     * @return
     */
    @Override
    public AjaxResult getConsumptionStatics(Long customerUid) {
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.put("code", 200);
        ajaxResult.put("msg", "操作成功");
        HashMap map = new HashMap();
        // 累计充值
        QueryWrapper<OrderRecharge> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("CUSTOMER_UID", customerUid);
        queryWrapper.eq("ORDER_STATUS", DataStatus.valid.getKey());
        queryWrapper.eq("PAY_STATUS", DataStatus.valid.getKey());
        queryWrapper.select("IFNULL(SUM(pay_Amount),0) pay_Amount");
        String cc = "0";
        OrderRecharge orderRecharge = orderRechargeMapper.selectOne(queryWrapper);
        if (ObjectUtil.isNotEmpty(orderRecharge)) {
            cc = MoneyUtils.changeF2B(orderRecharge.getPayAmount());
        }
        map.put("cc", cc);
        // 累计消费
        map.put("xf", orderInfoService.getOrderAmountByUid(customerUid));
        // 充值次数
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("CUSTOMER_UID", customerUid);
        queryWrapper.eq("ORDER_STATUS", DataStatus.valid.getKey());
        queryWrapper.eq("PAY_STATUS", DataStatus.valid.getKey());
        map.put("cs", orderRechargeMapper.selectCount(queryWrapper));
        ajaxResult.put("data",map);
        return ajaxResult;
    }

    /**
     * 查询充值订单
     *
     * @param rechargeUid 充值订单ID
     * @return 充值订单
     */
    @Override
    public OrderRecharge selectOrderRechargeById(Long rechargeUid) {
        return this.getById(rechargeUid);
    }

    /**
     * 查询充值订单列表
     *
     * @param orderRecharge 充值订单
     * @return 充值订单
     */
    @Override
    public List<OrderRecharge> queryList(OrderRecharge orderRecharge) {
        QueryWrapper<OrderRecharge> queryWrapper = Wrappers.query();
        if (StringUtils.isNotEmpty(orderRecharge.getPayMethod())){
            String[] pays = orderRecharge.getPayMethod().split(",");
            List<String> list = new ArrayList<>();
            for (String p:pays) {
                list.add(p);
            }
            orderRecharge.setPayMethodList(list);
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderRecharge.getRechargeUid())) && orderRecharge.getRechargeUid() != null) {
            queryWrapper.eq("RECHARGE_UID", orderRecharge.getRechargeUid());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderRecharge.getRechargeNo())) && orderRecharge.getRechargeNo() != null) {
            queryWrapper.like("RECHARGE_NO", orderRecharge.getRechargeNo());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderRecharge.getCustomerUid())) && orderRecharge.getCustomerUid() != null) {
            queryWrapper.eq("CUSTOMER_UID", orderRecharge.getCustomerUid());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderRecharge.getCustomerName())) && orderRecharge.getCustomerName() != null) {
            queryWrapper.like("CUSTOMER_NAME", orderRecharge.getCustomerName());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderRecharge.getPhone())) && orderRecharge.getPhone() != null) {
            queryWrapper.like("PHONE", orderRecharge.getPhone());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderRecharge.getOrderStatus())) && orderRecharge.getOrderStatus() != null) {
            queryWrapper.eq("ORDER_STATUS", orderRecharge.getOrderStatus());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderRecharge.getPayStatus())) && orderRecharge.getPayStatus() != null) {
            queryWrapper.eq("PAY_STATUS", orderRecharge.getPayStatus());
        }
        /*
        if (StringUtils.isNotEmpty(String.valueOf(orderRecharge.getPayMethod())) && orderRecharge.getPayMethod() != null) {
            queryWrapper.eq("PAY_METHOD", orderRecharge.getPayMethod());
        }*/
        if (orderRecharge.getPayMethodList() != null){
            queryWrapper.in("PAY_METHOD", orderRecharge.getPayMethodList());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderRecharge.getPlatSource())) && orderRecharge.getPlatSource() != null) {
            queryWrapper.eq("PLAT_SOURCE", orderRecharge.getPlatSource());
        }
        if (orderRecharge.getPayTimeArray() != null && orderRecharge.getPayTimeArray().size()>1){

            queryWrapper.between("PAY_TIME", orderRecharge.getPayTimeArray().get(0),orderRecharge.getPayTimeArray().get(1)+" 23:59:59");
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderRecharge.getPayTime())) && orderRecharge.getPayTime() != null) {
            queryWrapper.eq("PAY_TIME", orderRecharge.getPayTime());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderRecharge.getCancelTime())) && orderRecharge.getCancelTime() != null) {
            queryWrapper.eq("CANCEL_TIME", orderRecharge.getCancelTime());
        }
        /*
        if (ObjectUtil.isNotEmpty(orderRecharge.getStoreId())) {
            queryWrapper.eq("store_id", orderRecharge.getStoreId());
        }*/

        if (orderRecharge.getStoreIds() != null && orderRecharge.getStoreIds().size()>0) {
            queryWrapper.in("store_id", orderRecharge.getStoreIds());
        }

        queryWrapper.orderByDesc("CREATE_TIME");



        List<OrderRecharge> list = orderRechargeMapper.selectList(queryWrapper);
        if (list.size() > 0) {

            List<CustomerLevel> levels = customerLevelService.queryList(new CustomerLevel());

            Map<Long, String> map = new HashMap<>();
            for (CustomerLevel vo : levels) {
                map.put(vo.getLevelId(), vo.getLevelName());
            }
            for (OrderRecharge recharge : list) {
                if (recharge.getLevelId() != null &&  map.containsKey(recharge.getLevelId())) {
                    recharge.setLevelName(map.get(recharge.getLevelId()));
                }
            }
        }

        return list;
    }

    @Override
    public OrderRecharge sumQueryList(OrderRecharge orderRecharge) {
        QueryWrapper<OrderRecharge> queryWrapper = Wrappers.query();
        if (StringUtils.isNotEmpty(orderRecharge.getPayMethod())){
            String[] pays = orderRecharge.getPayMethod().split(",");
            List<String> list = new ArrayList<>();
            for (String p:pays) {
                list.add(p);
            }
            orderRecharge.setPayMethodList(list);
        }
        queryWrapper.select(" sum(pay_amount) as pay_amount ");
        if (StringUtils.isNotEmpty(String.valueOf(orderRecharge.getRechargeUid())) && orderRecharge.getRechargeUid() != null) {
            queryWrapper.eq("RECHARGE_UID", orderRecharge.getRechargeUid());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderRecharge.getRechargeNo())) && orderRecharge.getRechargeNo() != null) {
            queryWrapper.like("RECHARGE_NO", orderRecharge.getRechargeNo());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderRecharge.getCustomerUid())) && orderRecharge.getCustomerUid() != null) {
            queryWrapper.eq("CUSTOMER_UID", orderRecharge.getCustomerUid());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderRecharge.getCustomerName())) && orderRecharge.getCustomerName() != null) {
            queryWrapper.like("CUSTOMER_NAME", orderRecharge.getCustomerName());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderRecharge.getPhone())) && orderRecharge.getPhone() != null) {
            queryWrapper.like("PHONE", orderRecharge.getPhone());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderRecharge.getOrderStatus())) && orderRecharge.getOrderStatus() != null) {
            queryWrapper.eq("ORDER_STATUS", orderRecharge.getOrderStatus());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderRecharge.getPayStatus())) && orderRecharge.getPayStatus() != null) {
            queryWrapper.eq("PAY_STATUS", orderRecharge.getPayStatus());
        }
        /*
        if (StringUtils.isNotEmpty(String.valueOf(orderRecharge.getPayMethod())) && orderRecharge.getPayMethod() != null) {
            queryWrapper.eq("PAY_METHOD", orderRecharge.getPayMethod());
        }*/
        if (orderRecharge.getPayMethodList() != null){
            queryWrapper.in("PAY_METHOD", orderRecharge.getPayMethodList());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderRecharge.getPlatSource())) && orderRecharge.getPlatSource() != null) {
            queryWrapper.eq("PLAT_SOURCE", orderRecharge.getPlatSource());
        }
        if (orderRecharge.getPayTimeArray() != null && orderRecharge.getPayTimeArray().size()>1){

            queryWrapper.between("PAY_TIME", orderRecharge.getPayTimeArray().get(0),orderRecharge.getPayTimeArray().get(1)+" 23:59:59");
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderRecharge.getPayTime())) && orderRecharge.getPayTime() != null) {
            queryWrapper.eq("PAY_TIME", orderRecharge.getPayTime());
        }
        if (StringUtils.isNotEmpty(String.valueOf(orderRecharge.getCancelTime())) && orderRecharge.getCancelTime() != null) {
            queryWrapper.eq("CANCEL_TIME", orderRecharge.getCancelTime());
        }
        /*
        if (ObjectUtil.isNotEmpty(orderRecharge.getStoreId())) {
            queryWrapper.eq("store_id", orderRecharge.getStoreId());
        }*/

        if (orderRecharge.getStoreIds() != null && orderRecharge.getStoreIds().size()>0) {
            queryWrapper.in("store_id", orderRecharge.getStoreIds());
        }

        OrderRecharge rst = orderRechargeMapper.selectOne(queryWrapper);

        return rst;
    }

    /**
     * 新增充值订单
     *
     * @param orderRecharge 充值订单
     * @return 结果
     */
    @Override
    public boolean insertOrderRecharge(OrderRecharge orderRecharge) {

        return this.save(orderRecharge);

    }

    /**
     * 修改充值订单
     *
     * @param orderRecharge 充值订单
     * @return 结果
     */
    @Override
    public boolean updateOrderRecharge(OrderRecharge orderRecharge) {

        return this.updateById(orderRecharge);
    }

    /**
     * 生成父订单号
     *
     * @return
     */
    private String createParentOrderNo() {
        String time = String.valueOf(System.currentTimeMillis());
        String key = order_no_key + time;
        String orderNo = "PX" + time + redisService.incr(key, 1L, TimeUnit.SECONDS);
        return orderNo;
    }

    /**
     * 创建父订单
     *
     * @param settle
     * @return
     */
    private OrderInfoParent createParentOrder(OrderSettlementVo settle) {
        log.info("=================开始创建支付订单===================");
        //商品总额
        Long parentAmount = settle.getShopAmount();
        Long score = settle.getScoreAmount();

        if (settle.getFreight() == null) {
            settle.setFreight(0L);
        }
        if (settle.getRedBag() == null) {
            settle.setRedBag(0L);
        }
        if (settle.getBalance() == null) {
            settle.setBalance(0L);
        }
        if (settle.getScore() == null) {
            settle.setScore(0L);
        }
        if (settle.getDiscountAmount() == null) {
            settle.setDiscountAmount(0L);
            settle.setDiscountRate(0L);
        }
        if (settle.getCouponAmount() == null) {
            settle.setCouponAmount(0L);
            settle.setCouponRate(0L);
        }


        //现金支付金额
//        Long payAmount = parentAmount+settle.getFreight()-settle.getBalance()-settle.getRedBag()-settle.getDiscountAmount()-settle.getCouponAmount();
        Long payAmount = parentAmount + settle.getFreight() - settle.getBalance() - settle.getRedBag() - settle.getDiscountAmount() - settle.getCouponAmount();
        //update by liuhj 2021-08-18 20:27:01
        //如果出现负数，需要处理
        if (payAmount < 0) {
            if (settle.getBalance() > 0) {
                settle.setBalance(settle.getBalance() + payAmount);
            }
            payAmount = 0L;
        }
        OrderInfoParent parent = new OrderInfoParent();
        parent.setIsRecharge(settle.getIsRecharge());
        parent.setCreateTime(new Date());
        parent.setDiscountAmount(settle.getDiscountAmount());
        parent.setDiscountRate(settle.getDiscountRate());
        parent.setParentAmount(parentAmount);
        parent.setParentOrderNo(createParentOrderNo());
        parent.setPayAmount(payAmount);
        parent.setPayByScore(score);
        parent.setPayByBalance(settle.getBalance());
        //parent.setPayByScore(settle.getScore());
        parent.setFreightAmount(settle.getFreight());
        parent.setPayByRedBag(settle.getRedBag());
        parent.setPayMethod(settle.getPayMethod());
        parent.setPayStatus(PayStatusEnum.paid.getKey());
        parent.setPayTime(parent.getCreateTime());
        parent.setExpireDate(settle.getExpireDate());
        parent.setUseCouponUid(settle.getCouponId());
        parent.setUseCouponAmount(settle.getCouponAmount());
        parent.setProfitSharing(ProfitSharingEnum.N.toString());
        parent.setCustomerId(settle.getCustomerId());
        parent.setPlatformId(SecurityUtils.getCustomerPlatformUid());
        parent.setStoreId(settle.getStoreId());
        if (orderInfoParentService.save(parent)) {
            return parent;
        }
        throw new BaseException("创建订单失败，请稍后再试");
    }

    /**
     * 生成充值订单号
     */
    private String createRechargeOrderNo() {
        String time = String.valueOf(System.currentTimeMillis());
        String key = order_no_key + time;
        String orderNo = "RX" + time + redisService.incr(key, 1L, TimeUnit.SECONDS);
        return orderNo;
    }


    @Override
    public boolean recharge(OrderRecharge orderRecharge) {


        Long amount = 0L;
        Long totalAmount = 0L;

        RechargeInfo info = rechargeInfoService.getById(orderRecharge.getRechargeId());
        if (info == null || !info.getDataStatus().equals(DataStatus.valid.getKey())) {
            throw new BaseException("没有找到充值项");
        }
        PlatformStore store = platformStoreService.getById(orderRecharge.getStoreId());
        if (store == null || !store.getDataStatus().equals(DataStatus.valid.getKey())) {
            throw new BaseException("门店信息不存在");
        }
        CustomerInfo customerInfo =  iCustomerInfoService.getById(orderRecharge.getCustomerUid());
        if (customerInfo == null){
            throw new BaseException("会员信息不存在");
        }

        amount = info.getRechargeMoney();
        totalAmount = amount;

        if (amount == null || amount <= 0)
            throw new BaseException("储值金额需大于0元");
        OrderSettlementVo settle = new OrderSettlementVo();
        settle.setCustomerId(customerInfo.getCustomerUid());
        settle.setCustomerName(customerInfo.getCustomerName());
        settle.setPhone(customerInfo.getPhone());
        settle.setPlatformId(SecurityUtils.getCustomerPlatformUid());
        settle.setPlatSource(PlatSourceEnum.web.getKey());
        settle.setShopAmount(amount);
        settle.setPayMethod(PayMethodEnum.cashPayment.getKey());
        settle.setIsRecharge(OrderRechargeEnum.recharge.getKey());
        settle.setStoreId(orderRecharge.getStoreId());
        OrderInfoParent parent = createParentOrder(settle);

        Date now = new Date();
        OrderRecharge recharge = new OrderRecharge();
        recharge.setPlatformUid(SecurityUtils.getCustomerPlatformUid());
        recharge.setRechargeNo(createRechargeOrderNo());
        recharge.setRechargeName(info.getRechargeName());
        recharge.setParentOrderNo(parent.getParentOrderNo());
        recharge.setCustomerUid(customerInfo.getCustomerUid());
        recharge.setCustomerName(customerInfo.getCustomerName());
        recharge.setPhone(customerInfo.getPhone());
        recharge.setOrderStatus(OrderStatusEnum.effect.getKey());
        recharge.setPayStatus(PayStatusEnum.paid.getKey());
        recharge.setPayMethod(settle.getPayMethod());
        recharge.setPlatSource(settle.getPlatSource());
        recharge.setOrderAmount(totalAmount);
        recharge.setPayAmount(amount);
        recharge.setCurrencyUnit("RMB");
        recharge.setCreateTime(now);
        recharge.setBuyMes("线下收款");
        recharge.setIp(SecurityUtils.getCustomerClientIp());
        recharge.setRechargeId(info.getRechargeId());
        recharge.setFirstDouble(info.getFirstDouble());
        if (info.getFirstDoubleMonth() != null) {
            recharge.setFirstDoubleMonth(info.getFirstDoubleMonth().intValue());
        }
        recharge.setGoldCoin(info.getGoldCoin());
        recharge.setSilverCoin(info.getSilverCoin());
        recharge.setScore(info.getScore());
        recharge.setRechargeDesc(info.getRechargeDesc());
        recharge.setStoreId(settle.getStoreId());
        recharge.setIsShared(ProfitsharingStatusEnum.wait.getKey());
        recharge.setProfitSharing(ProfitSharingEnum.N.toString());
        recharge.setPayStatus(PayStatusEnum.paid.getKey());
        recharge.setPayTime(parent.getPayTime());
        //店铺配置获取支付超时时间
        Date expire = DateUtils.add(60L);
        recharge.setExpireDate(expire);
        recharge.setRemark(orderRecharge.getRemark());

        if (save(recharge)) {



            int rate = 1;
            if (DataStatus.valid.getKey().equals(recharge.getFirstDouble())){
                //是否首充双倍
                if (recharge.getFirstDoubleMonth()>0) {
                    RechargeRecord record = rechargeRecordService.selectRecharge(recharge.getRechargeId(), recharge.getCustomerUid());
                    if (record == null) {
                        rate = 2;
                    }else{
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(new Date());
                        int toDayMonth = calendar.get(Calendar.MONTH);
                        if (toDayMonth >= recharge.getFirstDoubleMonth()){
                            calendar.setTime(record.getCreateTime());
                            if (calendar.get(Calendar.MONTH)<toDayMonth){
                                rate = 2;
                            }
                        }
                    }
                }
            }

                CustomerFundVo fundVo = new CustomerFundVo();
                fundVo.setCustomerUid(parent.getCustomerId());
                fundVo.setBalance(recharge.getGoldCoin()*rate);
                fundVo.setBizNo(recharge.getRechargeNo());
                fundVo.setBizTime(recharge.getPayTime());
                fundVo.setStatus(DataStatus.valid.getKey());
                fundVo.setRemark("充值余额");
                fundVo.setStoreId(recharge.getStoreId());
                fundVo.setOrderUid(recharge.getRechargeUid());
                fundVo.setPlatformUid(recharge.getPlatformUid());
                if (recharge.getSilverCoin() != null && recharge.getSilverCoin() > 0) {
                    fundVo.setRedBag(recharge.getSilverCoin()*rate);
                }
                if (recharge.getScore() != null && recharge.getScore() > 0) {
                    fundVo.setScore(recharge.getScore()*rate);
                }
                //涨经验
                fundVo.setProfit(recharge.getPayAmount() / 100 * Constants.PROFIT_RATE);
                iCustomerFundService.addCustomerFund(fundVo);

                RechargeRecord record = new RechargeRecord();
                BeanUtils.copyProperties(info, record);
                record.setScore(fundVo.getScore());
                record.setGoldCoin(fundVo.getBalance());
                record.setSilverCoin(fundVo.getRedBag());
                record.setCreateTime(recharge.getCreateTime());
                record.setCreateName(SecurityUtils.getUsername());
                record.setCreateUser(SecurityUtils.getUserId());
                record.setStoreId(recharge.getStoreId());
                record.setDataStatus(DataStatus.valid.getKey());
                record.setMemberId(recharge.getCustomerUid());
                rechargeRecordService.save(record);

                List<RechargeRecordRights> rights = new ArrayList<>();
                List<RechargeRightItem> list = rechargeInfoService.getRightByRechargeId(recharge.getRechargeId());
                for (RechargeRightItem right : list) {

                    ProductInfo productInfo = null;
                    RechargeRecordRights recordRight = new RechargeRecordRights();
                    BeanUtils.copyProperties(record, recordRight);
                    recordRight.setRightType(right.getType());
                    recordRight.setRightId(right.getId());
                    recordRight.setRightAmount(right.getAmount());
                    recordRight.setRightObjectId(right.getId());
                    recordRight.setCreateName(record.getCreateName());
                    recordRight.setCreateTime(record.getCreateTime());
                    recordRight.setCreateUser(record.getCreateUser());

                    if (right.getType().equals(CardServiceTypeEnum.coupon.getKey())) {

                    } else if (right.getType().equals(CardServiceTypeEnum.card.getKey())) {


                    } else if (right.getType().equals(CardServiceTypeEnum.serviceItem.getKey())) {

                    } else if (right.getType().equals(CardServiceTypeEnum.good.getKey())) {
                        productInfo = iProductInfoService.getById(right.getId());
                        if (productInfo == null || !productInfo.getAuditStatus().equals(DataStatus.valid.getKey())) {

                        }
                    }
                    rights.add(recordRight);
                }
                if (rights.size() > 0) {
                    rechargeRecordRightsService.saveBatch(rights);
                }
            return true;
        }
        throw new BaseException("充值失败，请稍后再试");

    }

    /**
     * 批量删除充值订单
     *
     * @param rechargeUids 需要删除的充值订单ID
     * @return 结果
     */
    @Override
    public boolean deleteOrderRechargeByIds(Long[] rechargeUids) {
        return this.removeByIds(Arrays.asList(rechargeUids));
    }

    /**
     * 根据支付单号获取充值订单
     *
     * @param parentOrderNo
     * @return
     */
    @Override
    public OrderRecharge getByParentOrderNo(String parentOrderNo) {
        QueryWrapper<OrderRecharge> queryWrapper = Wrappers.query();
        queryWrapper.eq("PARENT_ORDER_NO", parentOrderNo);
        queryWrapper.eq("ORDER_STATUS", OrderStatusEnum.effect.getKey());
        List<OrderRecharge> list = orderRechargeMapper.selectList(queryWrapper);
        if (ObjectUtil.isNotEmpty(list))
            return list.get(0);
        return null;
    }

    @Override
    public List<OrderRecharge> listOrderRechargeByCustomerId(Long customerUid) {
        return orderRechargeMapper.listOrderRechargeByCustomerId(customerUid);
    }


}
